package com.medicine.web.controller.system;

import java.util.List;
import java.util.Map;

import com.medicine.common.core.domain.entity.SysUser;
import com.medicine.common.utils.SecurityUtils;
import com.medicine.manage.block.domain.UserExtend;
import com.medicine.manage.service.block.IBlockService;
import com.medicine.system.service.ISysRoleService;
import com.medicine.system.service.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.medicine.common.annotation.Log;
import com.medicine.common.constant.UserConstants;
import com.medicine.common.core.controller.BaseController;
import com.medicine.common.core.domain.AjaxResult;
import com.medicine.common.core.domain.entity.SysDept;
import com.medicine.common.enums.BusinessType;
import com.medicine.common.utils.StringUtils;
import com.medicine.system.service.ISysDeptService;

import javax.servlet.http.HttpServletRequest;

/**
 * 部门信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Value("${ruoyi.name}")
    private String name;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private IBlockService blockService;

    public static final Long DEFAULT_ROLE_ID = 100L;
    public static final String DEFAULT_ADMIN_PASSWORD = "123456";

    /**
     * 获取部门列表
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {


        //edit by li在添加药店是默认添加一个管理员
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        // 添加药店管理员用户添加时的校验
        SysUser user = new SysUser();

        user.setUserName(dept.getLeader());
        user.setNickName(dept.getDeptName() + "管理员");
        Long[] roleIds = new Long[]{DEFAULT_ROLE_ID};
        user.setRoleIds(roleIds);

        user.setCreateBy(getUsername());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }

        dept.setCreateBy(getUsername());
        int result = deptService.insertDept(dept);


        user.setDeptId(dept.getDeptId());
        user.setPassword(SecurityUtils.encryptPassword(DEFAULT_ADMIN_PASSWORD));
        userService.insertUser(user);

        //创建管理员区块链账户
        UserExtend userExtend = blockService.createAdminSignUser(user.getUserId(), user.getUserName());
        userExtend.setUserId(user.getUserId());

        // 使用管理员账户创建合约
        String contractAddressStr = blockService.deployContract(userExtend.getSignUserId());
        dept.setContractAddress(contractAddressStr);
        dept.setContractName(this.name+"-" + dept.getDeptName());
        deptService.updateDept(dept);

        return toAjax(result);
    }

    /**
     * 修改部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }


    @PostMapping("/container")
    public AjaxResult addContainer(HttpServletRequest request){
        System.out.println(request.getParameterMap().size());
        for (Map.Entry s : request.getParameterMap().entrySet()) {
            System.out.println(s.getKey() + ":" + s.getValue());
        }
        System.out.println(request.getParameter("name"));
//        if(!containerService.checkNumberUnique(container)){
//            return error("新增容器'" + container.getNumber() + "'失败，容器编号已存在");
//        }
//
//        int result = containerService.add(container);
//        return toAjax(result);
        return null;
    }
}
